'use strict';

import SessionStorage from './SessionStorage';
import { BASE_URL } from './Constants';

function buildParas(paras : {})  : string {
  var paraStr = "";

  if(!!paras &&  Object.keys(paras).length > 0) {
    var isFirst = true;
    for(var key in paras) {
      var value = encodeURIComponent(paras[key]);
      if(isFirst) {
        paraStr = paraStr + "?" + key + "=" + value;
        isFirst = false;
      } else
        paraStr = paraStr + "&" + key + "=" + value;
    }
  }

  return paraStr;
}

function fetch(async : boolean, type : string, uri : string, paras : {}, resolve : ()=>void, reject : ()=>void, httpTimeout ?: number = 300000) {
  var httpTimeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 300000;

  $.ajax({
    headers: {
      'charset': 'utf-8',
      'jwt': SessionStorage.getJwt(),
      'enterpriseId': SessionStorage.getEnterpriseId(),
      'employeeId': SessionStorage.getEmployeeId()
    },
    async: async,
    url: BASE_URL + uri + buildParas(paras),
    type: type,
    dataType: 'json',
    timeout: httpTimeout,
    complete: function complete(xhr, textStatus) {
      if(xhr.readyState == 4) {
        if(xhr.status == 200) {
          if(!!resolve)
            resolve(xhr.responseJSON, xhr.responseText);
        } else {
          if(!!reject)
            reject(xhr.responseJSON.errorMsg);
        }
      } else if(xhr.readyState == 0 && xhr.status == 0) {
        if(!!reject)
          reject('请稍后重试, 系统找不到');
      }
    }
  });
}

export function get(async : boolean, uri : string, paras : {}, resolve : ()=>void, reject : ()=>void, httpTimeout ?: number = 300000) {
  return fetch(async, "get", uri, paras, resolve, reject, httpTimeout);
}

export function del(async : boolean, uri : string, paras : {}, resolve : ()=>void, reject : ()=>void, httpTimeout ?: number = 300000) {
  return fetch(async, "delete", uri, paras, resolve, reject, httpTimeout);
}

function fetchWithData(async : boolean, type : string, uri : string, paras : {}, jsonData : string, resolve : ()=>void, reject : ()=>void, httpTimeout ?: number = 300000) {
  var httpTimeout = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 300000;

  $.ajax({
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'charset': 'utf-8',
      'jwt': SessionStorage.getJwt(),
      'enterpriseId': SessionStorage.getEnterpriseId(),
      'employeeId': SessionStorage.getEmployeeId()
    },
    async: async,
    url: BASE_URL + uri + buildParas(paras),
    type: type,
    data: jsonData,
    dataType: 'json',
    timeout: httpTimeout,
    complete: function complete(xhr, textStatus) {
      if(xhr.readyState == 4) {
        if(xhr.status == 200) {
          if(!!resolve)
            resolve(xhr.responseJSON, xhr.responseText);
        } else {
          if(!!reject)
            reject(xhr.responseJSON.errorMsg);
        }
      } else if(xhr.readyState == 0 && xhr.status == 0) {
        if(!!reject)
          reject('请稍后重试, 系统找不到');
      }
    }
  });
}

export function put(async : boolean, uri : string, paras : {}, jsonData : string, resolve : ()=>void, reject : ()=>void, httpTimeout ?: number = 300000) {
  return fetchWithData(async, "put", uri, paras, jsonData, resolve, reject, httpTimeout);
}

export function post(async : boolean, uri : string, paras : {}, jsonData : string, resolve : ()=>void, reject : ()=>void, httpTimeout ?: number = 300000) {
  return fetchWithData(async, "post", uri, paras, jsonData, resolve, reject, httpTimeout);
}

export function upload(async : boolean, uri : string, paras : {}, formdata : Formdata, resolve : ()=>void, reject : ()=>void, httpTimeout ?: number = 300000) {
  var httpTimeout = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 300000;

  $.ajax({
    headers: {
      'charset': 'utf-8',
      'jwt': SessionStorage.getJwt(),
      'enterpriseId': SessionStorage.getEnterpriseId(),
      'employeeId': SessionStorage.getEmployeeId()
    },
    async: async,
    url: BASE_URL + uri + buildParas(paras),
    type: 'post',
    data: formdata,
    cache: false,
    contentType: false,
    processData: false,
    timeout: httpTimeout,
    complete: function complete(xhr, textStatus) {
      if(xhr.readyState == 4) {
        if(xhr.status == 200) {
          if(!!resolve)
            resolve();
        } else {
          if(!!reject)
            reject(xhr.responseJSON.errorMsg);
        }
      } else if(xhr.readyState == 0 && xhr.status == 0) {
        if(!!reject)
          reject('请稍后重试, 系统找不到');
      }
    }
  });
}
